package com.adwhirl.adapters;

import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.View;

import com.adwhirl.AdWhirlLayout;
import com.adwhirl.AdWhirlLayout.ViewAdRunnable;
import com.adwhirl.obj.Extra;
import com.adwhirl.obj.Ration;
import com.adwhirl.util.AdWhirlUtil;
import com.tapit.adview.AdView;
import com.tapit.adview.AdViewCore.OnAdDownload;

/**
 * This file was provided by TapIt. Please contact synergyma@gmail.com with any
 * questions or concerns.
 */
public class TapItAdapter extends AdWhirlAdapter implements OnAdDownload {
	
	private AdView adView;

	public TapItAdapter(AdWhirlLayout adWhirlLayout, Ration ration) {
		super(adWhirlLayout, ration);
	}

	@Override
	public void handle() {
		AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
		if (adWhirlLayout == null) {
			return;
		}

		Activity activity = adWhirlLayout.activityReference.get();
		if (activity == null) {
			return;
		}

//		AdLog.setDefaultLogLevel(AdLog.LOG_LEVEL_3);
		adView = new AdView(activity, ration.key);

		adView.setOnAdDownload(this);
		Extra extra = adWhirlLayout.extra;
		int bgColor = Color.rgb(extra.bgRed, extra.bgGreen, extra.bgBlue);

		// int fgColor = Color.rgb(extra.fgRed, extra.fgGreen, extra.fgBlue);
		adView.setBackgroundColor(bgColor);

		adView.setUpdateTime(0);
		
	    if (extra.locationOn == 1 && adWhirlLayout.adWhirlManager.location != null) {
	    	adView.setLongitude(Double.toString(adWhirlLayout.adWhirlManager.location.getLongitude()));
	    	adView.setLatitude(Double.toString(adWhirlLayout.adWhirlManager.location.getLatitude()));
	    } else if (extra.locationOn == 0) {
			adView.setLongitude("0");
			adView.setLatitude("0");
		}
		adView.setBannerAnimationEnabled(false);
		adView.update(true);
		Log.d(AdWhirlUtil.ADWHIRL, "TapIt handle() finished");
	}

	@Override
	public void begin() {
		Log.d(AdWhirlUtil.ADWHIRL, "begin");
	}

	@Override
	public void end() {
		Log.d(AdWhirlUtil.ADWHIRL, "TapIt success");

		AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
		if (adWhirlLayout == null) {
			return;
		}
		
		adView.setOnAdDownload(null);
		adView.setVisibility(View.VISIBLE);

		adWhirlLayout.adWhirlManager.resetRollover();
		adWhirlLayout.handler.post(new ViewAdRunnable(adWhirlLayout, adView));
		adWhirlLayout.rotateThreadedDelayed();
	}

	@Override
	public void error(String arg0) {
		Log.d(AdWhirlUtil.ADWHIRL, "TapIt failure");
		adView.setOnAdDownload(null);

		AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
		if (adWhirlLayout == null) {
			return;
		}
		adWhirlLayout.rollover();
	}
}
